package com.faner.fast.upms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.faner.fast.base.PageDTO;
import com.faner.fast.constant.CacheConstants;
import com.faner.fast.constant.enums.DictTypeEnum;
import com.faner.fast.exception.FailedException;
import com.faner.fast.upms.mapper.SysDictItemMapper;
import com.faner.fast.upms.mapper.SysDictMapper;
import com.faner.fast.upms.model.SysDictDO;
import com.faner.fast.upms.model.SysDictItemDO;
import com.faner.fast.upms.service.SysDictService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 字典表
 */
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDictDO> implements SysDictService {

    private final SysDictItemMapper dictItemMapper;

    @Override
    public Page<SysDictDO> getSysDictPage(PageDTO page, SysDictDO sysDict) {
       return this.baseMapper.selectPage(new Page<>(page.getPageNum(), page.getPageSize()), Wrappers.lambdaQuery(sysDict));
    }


    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void removeDict(Long id) {
        SysDictDO dict = this.getById(id);
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystem())){
            throw new FailedException("系统内置字典项目不能删除");
        }
        baseMapper.deleteById(id);
        dictItemMapper.delete(Wrappers.<SysDictItemDO>lambdaQuery().eq(SysDictItemDO::getDictId, id));
    }


    @Override
    public void updateDict(SysDictDO dict) {
        SysDictDO sysDict = this.getById(dict.getId());
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystem())){
            throw new FailedException("系统内置字典项目不能修改");
        }
        this.updateById(dict);
    }

}
